<template>
  <div>
    <FilterTop></FilterTop>
    <a-divider>搜索到以下结果&nbsp;</a-divider>
    <SearchRouteResult v-for="route in routes.slice((currentPage - 1) * pageSize, currentPage * pageSize)"
      :key="route.id" :route="route" />
    <div style="text-align: center;">
      <!-- 底部分页器 -->
      <el-pagination background layout="total, prev, pager, next" :total="total" :current-page.sync="currentPage"
        @current-change="handlePageChange" :page-size="pageSize">
      </el-pagination>
    </div>
  </div>
</template>

<script>
import { loadRoutes } from '@/API/search'
import FilterTop from '@/components/Search/FilterTop.vue'
import { Message } from 'element-ui'
import SearchRouteResult from '../../components/Search/SearchRouteResult.vue'
import dayjs from 'dayjs'
export default {
  components: { FilterTop, SearchRouteResult },
  data() {
    return {
      input: this.$route.query.keyword,
      total: 0,
      currentPage: 1,
      pageSize: 6,
      loading: 1, //用于判断是否正在加载，若正在加载则显示骨架屏，否则显示搜索结果或搜索错误信息
      routes: [],
    }
  },
  methods: {
    handlePageChange(page) {
      this.currentPage = page
    },

  },
  mounted() {
    this.total = this.routes.length
    this.$bus.$on('orderBy', (order) => {
      if (order === 1) {
        this.routes.sort((a, b) => {
          return b.likes - a.likes
        })
      } else if (order === 2) {
        this.routes.sort((a, b) => {
          const time1 = dayjs(a.postTime)
          const time2 = dayjs(b.postTime)
          return time2.diff(time1)
        })
      } else if (order === 3) {
        this.routes.sort((a, b) => {
          return b.views - a.views
        })
      }
    })
  },

  beforeRouteUpdate(to, from, next) {
    next()
    loadRoutes(to.query.keyword)
      .then((res) => {
        if (res.data.code == 200) {
          this.loading = 0
          this.routes = res.data.data
          this.total = this.routes.length
        } else {
          Message({
            message: res.data.msg,
            type: 'error',
            customClass: 'error-message',
          })
        }
      })
      .catch((err) => {
        Message({
          message: err,
          type: 'error',
          customClass: 'error-message',
        })
      })
  },
  created() {
    loadRoutes(this.input)
      .then((res) => {
        if (res.data.code == 200) {
          this.loading = 0
          this.routes = res.data.data
          this.total = this.routes.length
        } else {
          Message({
            message: res.data.msg,
            type: 'error',
            customClass: 'search-error-message',
          })
        }
      })
      .catch((err) => {
        Message({
          message: err,
          type: 'error',
          customClass: 'search-error-message',
        })
      })
  },
  beforeDestroy() {
    this.$bus.$off('orderBy')
  },
}
</script>

<style>
.search-error-message {
  margin-top: 80px;
  z-index: 9999 !important;
}
</style>